package com.example.yiqinmanagersystem.controller.api;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.yiqinmanagersystem.entity.NocvNews;
import com.example.yiqinmanagersystem.service.NocvNewsService;
import com.example.yiqinmanagersystem.vo.NocvNewsVo;
import com.example.yiqinmanagersystem.vo.ResponseCode;
import com.example.yiqinmanagersystem.vo.ResponseResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/*
 **@Author:youpeng
 **Created on 2022/9/18
 */
@RestController
@RequestMapping("/api")
public class NocvNewsController {

    @Resource
    private NocvNewsService nocvNewsService;

    /*
    * 删除新闻 id
    * */
    @PostMapping("/news/deleteById")
    public ResponseResult deleteById(Integer id){
        boolean b = nocvNewsService.removeById(id);
        if(b){
            return new ResponseResult(ResponseCode.SUCCESS);
        }else {
            return new ResponseResult(ResponseCode.FAILED);
        }
    }

    /*
    * 带条件查询 新闻数据
    * */
    @GetMapping("/news/listNews")
    public ResponseResult listNews(NocvNewsVo nocvNewsVo){
        //1.条件
        IPage<NocvNews> page = new Page<>(nocvNewsVo.getPage(), nocvNewsVo.getLimit());
        QueryWrapper<NocvNews> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNoneBlank(nocvNewsVo.getTitle()),"title",nocvNewsVo.getTitle());
        queryWrapper.like(StringUtils.isNoneBlank(nocvNewsVo.getPublishby()),"publishby",nocvNewsVo.getPublishby());
        //2.查库
        IPage<NocvNews> newsIPage = nocvNewsService.page(page, queryWrapper);
        if(newsIPage.getSize()>0){
            return new ResponseResult(ResponseCode.SUCCESS, Math.toIntExact(newsIPage.getTotal()),newsIPage.getRecords());
        }else {
            return new ResponseResult(ResponseCode.FAILED);
        }
    }

    /*
    * 新增（修改）新闻数据
    * */
    @PostMapping("/news/addOrUpdateNews")
    public ResponseResult addOrUpdateNews(NocvNews nocvNews){
        boolean b = nocvNewsService.saveOrUpdate(nocvNews);
        if(b){
            return new ResponseResult(ResponseCode.SUCCESS);
        }else {
            return new ResponseResult(ResponseCode.FAILED);
        }
    }
}
